package com.itmayiedu.core.handler;

import org.apache.log4j.Logger;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * Created by Devin on 2018/1/27.
 * WebLog拦截请求
 */
@Component
@Aspect
public class WebLogHandler {
    private Logger logger = Logger.getLogger(getClass());

    @Pointcut("execution(public * com.itmayiedu.controller..*.*(..))")
    public void webLog(){

    }
    @Before("webLog()")
    public void doBefor() throws Throwable{

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        logger.info("------------------------------------------------------------");
        logger.info("URL: "+request.getRequestURL().toString());
        logger.info("HTTP Method: "+request.getMethod());
        logger.info("IP: "+request.getRemoteAddr());
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()){
            String name = enu.nextElement();
            logger.info("name:{},value:{}"+name+request.getParameter(name));
        }
        logger.info("------------------------------------------------------------");

    }
    @AfterReturning(returning = "obj",pointcut = "webLog()")
    public void doAfterReturning(Object obj) throws Throwable{
        logger.info("Response: "+obj);
    }
}
